import {createRouter, createWebHistory} from "vue-router";
import {useUserStore} from "@/store/index.js";
import {Base64} from "js-base64";
import {getRequest} from "@/util/request.js";

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/login",
            component: () => import('@/views/Login.vue'),
        },
        {
            path: "/",
            meta: {whiteList: true},
            redirect: "/console/home"
        },
        {
            path: "/console",
            component: () => import("@/layout/Console.vue"),
            name: "console",
            children: [
                {
                    path: '',
                    name: 'redirectHome',
                    redirect: "/console/home"
                },
                {
                    path: 'home',
                    component: () => import ("@/views/console/Home.vue"),
                    // component: () => import ("@/views/console/permission/Role.vue"),
                },
            ]
        },
        {
            path: "/:pathMatch(.*)*",
            meta: {whiteList: true},
            component: () => import('@/views/error/404.vue'),
        },
    ]
})

router.beforeEach(function (to, from, next) {
    let isLogin = localStorage.getItem("tokenName");
    if (to.path === "/login" || to.path === "/register") {
        if (isLogin) {
            next(to.query.path ? Base64.decode(to.query.path) : '/');
        } else {
            next();
        }
    } else {
        if (isLogin) {
            let userStore = useUserStore();
            getRequest("/user/getInfo").then(res => {
                userStore.user = res.data;
                next()
            })
        } else {
            if (to.meta.whiteList) {
                next();
            } else {
                next("/login?path=" + Base64.encode(to.fullPath));
            }
        }
    }
})

export default router;